package httpserver

import (
	"core/coreentity"
	"core/corestruct"
	"core/coreutil"
	"core/datetime"
	"core/db"
	"core/logger"
	"core/myerrors"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"strings"
	"time"
)

var (
	HttpEngine *gin.Engine
)

func InitHttpServer() {
	if Config.Mode == "debug" {

	} else {
		gin.SetMode(gin.ReleaseMode)
	}
	HttpEngine = gin.New()
	HttpEngine.Use(Cors())
	HttpEngine.Use(GinFirst())
	HttpEngine.Use(GinAction())

	HttpEngine.NoRoute(func(c *gin.Context) {
		if c.Writer != nil && c.Writer.Size() > 0 {
			return
		}

		c.AbortWithStatusJSON(http.StatusOK, gin.H{
			"code": 404,
			"msg":  "未找到对应路径",
			"data": "",
		})

	})
}
func RunHttpServer() {
	go HttpEngine.Run("" + ":" + strconv.Itoa(Config.Port))
	logger.Logger.Info("Http服务启动 端口：" + strconv.Itoa(Config.Port))

}

func HttpOK(ctx *corestruct.HttpContext, p interface{}) {
	var c = ctx.Http
	c.AbortWithStatusJSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "",
		"data": p,
	})
}
func HttpMsg(ctx *corestruct.HttpContext, code int, msg string, data string) {
	var c = ctx.Http
	c.AbortWithStatusJSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  msg,
		"data": data,
	})
}
func HttpErr(ctx *corestruct.HttpContext, err any) {
	var c = ctx.Http
	path := c.Request.URL.Path
	query := c.Request.URL.RawQuery

	var myerr = myerrors.GetMyError(err)
	if strings.HasPrefix(myerr.InnerMsg, "UNIQUE ") {
		myerr = *myerrors.New("数据重复")
	}
	if myerr.Id == myerrors.ERROR_UNKNOW {
		//未知异常
		coreutil.Logger.Error(path,
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.String("query", query),
			zap.String("ip", c.ClientIP()),
			zap.String("user-agent", c.Request.UserAgent()),
			zap.String("error", myerr.FullMsg()),
		)
		HttpMsg(ctx, myerrors.ERROR_UNKNOW, "未知异常", myerr.FullMsg())

		var mhterr = &coreentity.HtError{
			Id:            coreutil.IdUtil.GetId(),
			Host:          Config.ServerName,
			Url:           ctx.GetUrl(),
			Memo:          "",
			Glid:          ctx.Glid,
			Pin:           "",
			ExClsname:     "",
			ExMsg:         "",
			ExFullmsg:     myerr.FullMsg(),
			HtplatId:      ctx.Session.HtplatId,
			Ip:            ctx.GetIp(),
			Browser:       ctx.GetBrowser(),
			Appver:        "",
			Name:          ctx.Session.Name,
			HtdeptId:      ctx.Session.HtdeptId,
			HtuserloginId: ctx.Session.Id,
			HtdeptName:    ctx.Session.HtdeptName,
			CrtDt:         datetime.Now(),
			CrtUid:        ctx.Session.CrtUid,
			CrtDid:        ctx.Session.HtdeptId,
		}
		if myerr.Err != nil {
			mhterr.ExMsg = myerr.Err.Error()
		}
		if ctx.Pin != nil {
			mhterr.Pin, _ = coreutil.Json.Marshal(ctx.Pin)
		}
		db.DbMaster.Create(mhterr)
	} else {
		HttpMsg(ctx, myerr.Id, myerr.Msg, "")
	}

}

func AddActoinLog(ctx *corestruct.HttpContext) {
	if ctx.Act == nil || ctx.Act.LogNeed == false {
		return
	}
	vstart, _ := ctx.Http.Get("start")
	var start = vstart.(time.Time)
	cost := time.Since(start)
	var su = ctx.Session
	var mhtlog = &coreentity.HtActionLog{
		Id:            coreutil.IdUtil.GetId(),
		Host:          Config.ServerName,
		Url:           ctx.GetUrl(),
		Memo:          "",
		Glid:          ctx.Glid,
		Pin:           "",
		Pout:          "",
		Mseconds:      int(cost.Milliseconds()),
		HtplatId:      su.HtplatId,
		HtuserloginId: su.Id,
		Ip:            ctx.GetIp(),
		Browser:       ctx.GetBrowser(),
		Appver:        "",
		Name:          su.Name,
		HtdeptId:      su.HtdeptId,
		HtdeptName:    su.HtdeptName,
		CrtDt:         datetime.Now(),
		CrtUid:        su.CrtUid,
		CrtDid:        su.HtdeptId,
	}
	if ctx.Act.LogPin && ctx.Pin != nil {
		mhtlog.Pin, _ = coreutil.Json.Marshal(ctx.Pin)
	}
	if ctx.Act.LogPout && ctx.Pout != nil {
		mhtlog.Pout, _ = coreutil.Json.Marshal(ctx.Pout)
	}
	if ctx.LogMemo == "" {
		if ctx.LogName == "" {
			var LogName = ""
			if ctx.Pin != nil {
				var name = coreutil.StructUtil.GetFieldValue(ctx.Pin, "Name")
				if name != nil {
					LogName = name.(string)
				}
			}
			mhtlog.Memo = ctx.Act.Name + " " + LogName
		} else {
			mhtlog.Memo = ctx.Act.Name + " " + ctx.LogName
		}
	} else {
		mhtlog.Memo = ctx.LogMemo
	}

	if ctx.Glid == "" {
		if ctx.Pin != nil {
			var Id = coreutil.StructUtil.GetFieldValue(ctx.Pin, "Id")
			if Id != nil {
				mhtlog.Glid = strconv.FormatInt(Id.(int64), 10)
			}
		}
	} else {
		mhtlog.Glid = ctx.Glid
	}

	db.DbMaster.Create(mhtlog)
}
